package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver;

    public static WebDriver createDriver(){
        //如果不存在driver对象,则创建driver对象
        if (driver == null){
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            //自定义安装的谷歌浏览器文件路径
            options.setBinary("D:\\其他软件\\Google\\Chrome\\Application\\chrome.exe");
            //允许访问所有链接
            options.addArguments("--remote-allow-origins=*");
            //设置页面加载策略为 NONE
            options.setPageLoadStrategy(PageLoadStrategy.NONE);
            driver = new ChromeDriver(options);

            //隐试等待2s
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        }
        return driver;
    }
    public  Utils(String url){
        //调用driv对象

        driver = createDriver();
        //访问URL
        driver.get(url);
    }
    //保存图片 存在image文件夹里
    public void getPicture(String str) throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        String filename = "D:\\工作软件\\IDEA\\项目\\baidutieba\\src\\test\\image\\"+ dirTime + "/" + str + "_" + fileTime + ".png";

        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(filename));
    }
}
